<template>
  <div class="container">
    <el-card class="tree-card">
      <div class="head">
        <span class="sbject-span-size">学科名称</span>
        <el-input class="inputInfo" size="mini" v-model="input"> </el-input>
        <el-button size="mini" @click="clearList">清除</el-button>
        <el-button type="primary" size="mini" @click="getSearch(input)"
          >搜索</el-button
        >
        <el-button
          type="success"
          style="float: right"
          size="mini"
          icon="el-icon-edit"
          @click="addSubject()"
          >新增学科</el-button
        >
        <el-alert type="info" show-icon class="alert-message" :closable="false">
          <span>数据一共{{ pagination.total }}条</span>
        </el-alert>
      </div>
      <template>
        <el-table :data="getList" stripe style="width: 100%; height: 100%">
          <el-table-column type="index" label="序号" width="50">
          </el-table-column>
          <el-table-column prop="subjectName" label="学科名称" width="100">
          </el-table-column>
          <el-table-column prop="username" label="创建者" width="120">
          </el-table-column>
          <el-table-column prop="addDate" label="创建日期" width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.addDate | getDay("{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="isFrontDisplay"
            label="前台是否显示"
            width="110"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.isFrontDisplay === 1 ? "是" : "否" }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="twoLevelDirectory"
            label="二级目录"
            width="100"
          >
          </el-table-column>
          <el-table-column prop="tags" label="标签" width="120">
          </el-table-column>
          <el-table-column
            prop="twoLevelDirectory"
            label="题目数量"
            width="100"
          >
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="230">
            <!-- slot-scope="scope" -->
            <template slot-scope="{ row }">
              <!-- @click="handleClick(scope.row)" -->
              <el-button type="text" size="small" @click="subjectSort(row)"
                >学科分类</el-button
              >
              <el-button type="text" size="small" @click="subjectLabelF(row)"
                >学科标签</el-button
              >
              <el-button type="text" size="small" @click="editSubject(row)"
                >修改</el-button
              >
              <el-button type="text" size="small" @click="deleteSubject(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end" style="height: 40px" align="middle">
          <el-pagination
            background
            small
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="[2, 4, 6, 10]"
            :current-page.sync="pagination.page"
            layout=" prev,pager, next,sizes, jumper"
            :total="pagination.total"
          >
            <!-- size-change  pagesize改变时会触发,   每页条数 -->
            <!-- current-change currentPage改变时会触发   当前页 -->
            <!-- 使用了size-change 页大小,有多少数据 和current-change当前页 事件来处理页码大小和当前页变动时候触发的事件。 -->
            <!-- size-change和 current-change事件 -->
            <!-- size-change -->
            <!-- :page-siezes="[2,4,6,10]" // 调整每页显示条数 选择上拉-->
          </el-pagination>
        </el-row>
      </template>
    </el-card>
    <!-- 新增学科 -->
    <!-- :title="roleForm.id ? '新增学科' : '编辑'" -->

    <el-dialog
      :title="subjectId.data.id ? '修改学科' : '新增学科'"
      :visible.sync="dialogVisible"
      width="50%"
      @close="btnCancle"
    >
      <el-form
        ref="roleForm"
        :rules="rules"
        :model="roleForm"
        label-width="80px"
      >
        <el-form-item label="角色描述" prop="subjectName">
          <el-input v-model="roleForm.subjectName" />
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch
            v-model="roleForm.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <el-row slot="footer" type="flex" justify="center" class="dialog-footer">
        <div>
          <el-button @click="btnCancle">取消</el-button>
          <el-button type="primary" @click="btnOk(roleForm)">确定</el-button>
          <!-- <el-button type="primary" @click="updateSubject()">确定</el-button> -->
          <!-- updateSubject -->
        </div>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { list, add, detail, remove, update } from '../../api/hmmm/subjects'
import { parseTimeByString } from '../../filters/index.js'
export default {
  data () {
    // 验证是否重复校验
    var validatePass = async (rule, value, callback) => {
      // roleForm.subjectName 就是value
      // 里面有数据,value在里面查找,是否存在相同的
      this.tableData.forEach((item) => {
        // 永远都是第一个item.subjectName
        if (item.subjectName !== value) {
          console.log('全部都不相同,可以通过了')
        } else {
          callback(new Error('至少有一个相同的学科了'))
        }
      })
    }
    return {
      // 新增学科
      dialogVisible: false,
      switchOpen: true,
      roleForm: {
        subjectName: '',
        isFrontDisplay: true
      },
      // 定义验证规则:
      rules: {
        subjectName: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ]
      },

      // 这是绑定的当前页面存放的一列一列的数据
      getList: [],
      // 这是请求的所有数据
      tableData: [],
      // 每页的条数
      // pagesize: '1',
      // 搜索栏v-model绑定的值
      input: '',
      // 学科Id
      subjectId: {
        data: {
          id: ''
        },
        subjectName: ''
      },
      // 每次请求列表数据需要携带的对象
      pagination: {
        page: 1, // 当前页码
        pagesize: 10, // 每页条数
        subjectName: null,
        // 所有数据条数
        total: null
      },
      paginationTotal: {
        page: 1,
        pagesize: 10000
      },
      // 学科分类传参
      subjectNameSort: '',
      // 学科分类id
      subjectNameSortId: '',
      // 学科标签
      subjectLabel: '',
      subjectLabelId: ''
    }
  },
  filters: {
    getDay (time) { // 时间格式化
      return parseTimeByString(time) // 格式化日期
    }
  },
  created () {
    this.getAllList()
  },
  methods: {
    // 学科分类传参------------------------------------------
    async subjectSort (row) {
      const result = await detail(row)
      this.subjectNameSort = result.data.subjectName
      this.subjectNameSortId = result.data.id
      // #/subjects/directorys?id= 168name=大数据
      this.$router.push({ path: `/subjects/directorys?id=${this.subjectNameSortId}&name=${this.subjectNameSort}` })
    },
    // 学科标签----------------------------
    async subjectLabelF (row) {
      const result = await detail(row)
      this.subjectLabel = result.data.subjectName
      this.subjectLabelId = result.data.id
      this.$router.push({ path: `/subjects/tags?id= ${this.subjectLabelId}&name=${this.subjectLabel}}` })
    },
    // 删除接口--------------------------------------------
    async deleteSubject (row) {
      const result = await remove(row)
      console.log('resultremove', result)
      this.$message({
        message: '删除成功',
        type: 'warning'
      })
      this.getAllList() // 重新刷新页面,且回到第一页
    },
    // 在一页上获取所有数据------------------------------------------
    async getAllListTotal (paginationTotal) {
      const result2 = await list(paginationTotal)
      // console.log('paginationTotal', result2)
      this.tableData = result2.data.items
      // console.log(this.tableData)
    },
    // 获取当前页所有数据-----------------------------------------------
    async getAllList () {
    // 重新渲染数据,重新赋予总条数
      const result = await list(this.pagination)
      // 总条数
      this.pagination.total = result.data.counts
      // console.log('result', result)
      // 所有数据
      this.getList = result.data.items
      // console.log(this.pagination)
      // console.log('getList', this.getList)
    },
    // 搜索方法---------------------------------------------------
    async getSearch (data) {
      this.pagination.page = 1
      this.pagination.subjectName = data
      const result = await list(this.pagination)
      this.getAllList(result.data.items) // 重新调用获取数据接口,渲染视图
    },

    // 新增学科按钮------------------------------------------------------
    addSubject () {
      this.getAllListTotal(this.paginationTotal)
      this.dialogVisible = true
      this.subjectId.data.id = ''
      this.roleForm.subjectName = ''
    },
    // 取消按钮:----------------------------------------------------------
    btnCancle () {
      // 表单重置
      this.$refs.roleForm.resetFields()
      this.dialogVisible = false
    },
    // 点击修改按钮,还原信息-----------------------------------------------------
    async editSubject (row) {
      const result = await detail(row)
      console.log('result', result)
      // 赋予subjectId,给予它标识
      this.subjectId.data = result.data
      console.log('this.subjectId.data', this.subjectId.data)
      this.roleForm.subjectName = result.data.subjectName
      this.dialogVisible = true
      // 确保打开后显示正确
      if (result.data.isFrontDisplay === 1) {
        this.roleForm.isFrontDisplay = true
      } else {
        this.roleForm.isFrontDisplay = false
      }
      console.log(result)
    },

    // 确认新增学科----------------------------------------------------------
    async btnOk (roleForm) {
      // 根据id来判断是修改还是新增
      if (this.subjectId.data.id !== '') {
        // 确认修改更新学科信息---------
        this.subjectId.data.subjectName = roleForm.subjectName
        const result = await update(this.subjectId.data, this.subjectId.data.subjectName)
        console.log('updateSubject', result)
        this.getAllList()
        this.$message({
          message: '修改学科成功',
          type: 'success'
        })
        this.dialogVisible = false
        this.subjectId.data.id = ''
      } else {
        try {
          await this.$refs.roleForm.validate()
          if (roleForm.isFrontDisplay === true) {
            this.roleForm.isFrontDisplay = 1
          } else {
            this.roleForm.isFrontDisplay = 0
          }
          const result = await add(roleForm) // 调用添加接口,得到新增学科信息
          console.log(result)
          // console.log('isFrontDisplay', roleForm.isFrontDisplay)
          this.dialogVisible = false // 对话框关闭
          this.roleForm.isFrontDisplay = true // 验证规则中的按钮,重新返回为true,默认为显示
          this.pagination.page = 1
          this.getAllList() // 重新刷新页面,且回到第一页
          this.$message({
            message: '新增学科成功',
            type: 'success'
          })
        } catch (e) {
          console.log(e)
        }
      }
      // 新增结束之后,subjectId再次清空
      this.subjectId.data.id = ''
      this.subjectId.subjectName = ''
    },

    // 每页显示信息条数------------------------------------------------
    handleSizeChange (pagesize) {
      // pagesize 每页条数,改变时会触发
      console.log('每页条数,改变时会触发')
      this.pagination.pagesize = pagesize // 每页条数,改变时会触发
      this.pagination.page = 1 // 回到第一页
      console.log(this.pagination.pagesize)
      this.getAllList()
    },
    handleCurrentChange (page) { // 当前页发生改变时候会触发
      console.log('当前页发生改变时候会触发', page)
      this.pagination.page = page
      this.getAllList()
    },
    // 清除-----------------------------------------------------------
    clearList () {
      this.input = ''
    }
  }
}
</script>

<style scoped lang='scss'>
.inputInfo {
  width: 200px;
  margin: 0 10px;
}
.sbject-span-size {
  font-weight: bold;
  font-size: 16px;
  color: #616267;
}
.alert-message {
  margin: 20px 0px;
}
</style>
